package cn.nfwx.tv.controller.player;

import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chan.net.HttpCallback;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.nfwx.tv.R;
import cn.nfwx.tv.activity.CcpActivity;
import cn.nfwx.tv.base.BaseDialogFragment;
import cn.nfwx.tv.base.NFWXApplication;
import cn.nfwx.tv.callback.ResponseWithFailListener;
import cn.nfwx.tv.controller.DownloadM3u8Controller;
import cn.nfwx.tv.controller.SceneChooseController;
import cn.nfwx.tv.controller.ShortVideoShareViewController;
import cn.nfwx.tv.controller.TVCompanyViewController;
import cn.nfwx.tv.controller.TVHotViewController;
import cn.nfwx.tv.controller.TVProgramsViewController;
import cn.nfwx.tv.db.AppDatabase;
import cn.nfwx.tv.db.DownProgramDao;
import cn.nfwx.tv.db.DownProgramModel;
import cn.nfwx.tv.events.AppointEvent;
import cn.nfwx.tv.events.PlayEvents;
import cn.nfwx.tv.fragment.dialog.ReviewShareDialogFragment;
import cn.nfwx.tv.fragment.dialog.WifiNoteFragment;
import cn.nfwx.tv.fragment.dialog.WifiSelectDialogFragment;
import cn.nfwx.tv.fragment.me.MineFragment;
import cn.nfwx.tv.fragment.search.SearchFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.ActivityHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.LocationHelper;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.PermissionHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.manager.NFWXWiFiManager;
import cn.nfwx.tv.manager.TVChannelManager;
import cn.nfwx.tv.manager.WatchRecordManager;
import cn.nfwx.tv.model.Company;
import cn.nfwx.tv.model.CompanyVideo;
import cn.nfwx.tv.model.DateProgram;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.TvChannel;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.okhttp.CustomOkHttpClient;
import cn.nfwx.tv.okhttp.UrlHelper;
import cn.nfwx.tv.util.AppUtil;
import cn.nfwx.tv.util.GlideUtil;
import cn.nfwx.tv.util.MobAgentUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.TSnackbarUtil;
import cn.nfwx.tv.util.TimeUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.util.WifiSupport;
import cn.nfwx.tv.widget.nfwxplayer.NfwxVideoPlayerManager;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LivePlayerController extends BasePlayerController implements Callback, ResponseWithFailListener<String>, Handler.Callback, WifiNoteFragment.onWifiNoteClick, NFWXWiFiManager.OnWiFiAvailableListener, Comparator<TvProgram> {

    private List<TvChannel> tvChannels = new ArrayList<>();
    private List<Company> companyList = new ArrayList<>();

    private String requestTvChannelCommand, requestTvChannelRefreshCommand, requestCompanyVideoCommand, requestReviewVodCommand;
    private final int actionTvChannelCommand = 1;
    private final int actionCompanyVideoCommand = 2;
    private final int actionReviewVodCommand = 3;
    private final int actionChannelRefreshCommand = 4;
    private int _position = -1;
    private String preChannelName;
    private String gid;
    private TvProgram mTvProgram;
    private TvProgram mNextProgram;
    private boolean _isLive = true;
    private boolean _isAdvert = false;
    private boolean _isPic;
    private boolean _isShift;
    private boolean _isAudio;
    private boolean _isHotDialog;
    private boolean _isDownLoaded;
    private boolean _isCompany;
    private String onShot = "";

    private PlayEvents events;
    private long cutBeginTime = -1;
    private long playBeginTime = -1;

    private static final int ACTION_PROGRAM_REFRESH = 9;
    private static final int ACTION_CHANNEL_REFRESH = 10;
    private static final int ACTION_PROGRAM_NEXT = 11;
    private static final int PROGRAM_DURING = 3 * 60 * 1000;

    private SimpleDateFormat dateFormat;

    private String mPath;

    public LivePlayerController(@NonNull Context context) {
        super(context);
    }

    private Handler mDataHandler;

    private int fromState;

    public static final int FROM_NONE = 0;
    public static final int FROM_REVIEW = 1;
    public static final int FROM_HOTVIEW = 2;
    public static final int FROM_OTHERS = 3;

    @Override
    protected void initView() {
        super.initView();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        findView(R.id.review_btn).setVisibility(View.GONE);
        player_bar.hideQpopWIFI();
        setDataHandler();
        setBackgroundHandler();
        fromState = FROM_NONE;
    }

    private void setDataHandler() {
        mDataHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case actionCompanyVideoCommand:
                        Bundle bundle = msg.getData();
                        String response = bundle.getString("data");
                        Result<List<Company>> result = JSON.parseObject(response, new TypeReference<Result<List<Company>>>() {
                        }.getType());
                        if (result != null && result.getMessage().equals(Result.RESULT_SUCCESS)) {
                            List<Company> companies = result.getData();
                            if (companies.isEmpty()) {
                                companyList.clear();
                                company_btn.setVisibility(View.GONE);
                            } else {
                                companyList.clear();
                                companyList.addAll(companies);
                                company_btn.setVisibility(View.VISIBLE);
                            }
                        }
                        break;
                    case actionReviewVodCommand:
                        bundle = msg.getData();
                        List<TvProgram> tvPrograms = bundle.getParcelableArrayList("data");
                        channelAdapter.notifyItemChanged(_position, tvChannels.get(_position));
                        pcv_home.setProgramSeek(tvPrograms);
                        pcv_home.refreshProgramSeek();
                        break;
                    case actionChannelRefreshCommand:
                        bundle = msg.getData();
                        List<TvChannel> channels = bundle.getParcelableArrayList("data");
                        List<TvChannel> preChannels = new ArrayList<>(tvChannels);
                        tvChannels.clear();
                        tvChannels.addAll(channels);
                        channelAdapter.setNewData(new ArrayList<Object>(channels));
                        if (_position >= 0 && !preChannels.isEmpty()) {
                            TvChannel tvChannel = preChannels.get(_position);
                            for (int i = 0; i < channels.size(); i++) {
                                TvChannel channel = channels.get(i);
                                if (tvChannel.getGid().equals(channel.getGid())) {
                                    if (!TextUtils.isEmpty(channel.getUrl())
                                            && !channel.getUrl().equals(tvChannel.getUrl())) {
                                        if (isLive()) {
                                            _position = -1;
                                            play(i);
                                        } else {
                                            _position = i;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                        break;
                }
                return false;
            }
        });
    }

    private void setBackgroundHandler() {
        HandlerThread handlerThread = new HandlerThread(REFRESH_BACKGROUND_HANDLER);
        handlerThread.start();
        backgroundHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case ACTION_PROGRAM_REFRESH:
                        if (_position >= 0 && _position < tvChannels.size()) {
                            tvChannels.get(_position).getTvPrograms().clear();
                            tvChannels.get(_position).getDatePrograms().clear();
                            loadTvPrograms(tvChannels.get(_position));
                            //tvChannels.get(_position).loadPrograms(mContext, null);
                        }
                        backgroundHandler.removeMessages(ACTION_PROGRAM_REFRESH);
                        backgroundHandler.sendEmptyMessageDelayed(ACTION_PROGRAM_REFRESH, PROGRAM_DURING);
                        break;
                    case ACTION_CHANNEL_REFRESH:
                        RxAppCompatActivity activity = (RxAppCompatActivity) AppUtil.getAppCompActivity(mContext);
                        requestTvChannelRefreshCommand = TVChannelManager.getChannelLives(mContext, activity.<com.chan.net.Result<List<TvChannel>>>bindToLifecycle(), new HttpCallback<List<TvChannel>>() {
                            @Override
                            public void onSuccess(String requestCommand, com.chan.net.Result<List<TvChannel>> data) {
                                String liveStr = SharePrefUtil.getLivestr(mContext);
                                String str = JSON.toJSONString(data.getData());
                                if (!liveStr.equals(str)) {
                                    SharePrefUtil.saveLiveStr(mContext, str);
                                    tvChannels.clear();
                                    tvChannels.addAll(data.getData());
                                    channelAdapter.setNewData(new ArrayList<Object>(data.getData()));
                                    if (_position >= 0 && !data.getData().isEmpty()) {
                                        TvChannel tvChannel = data.getData().get(_position);
                                        for (int i = 0; i < data.getData().size(); i++) {
                                            TvChannel channel = data.getData().get(i);
                                            if (tvChannel.getGid().equals(channel.getGid())) {
                                                if (!TextUtils.isEmpty(channel.getUrl())
                                                        && !channel.getUrl().equals(tvChannel.getUrl())) {
                                                    if (isLive()) {
                                                        _position = -1;
                                                        play(i);
                                                    } else {
                                                        _position = i;
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onFail(String requestCommand, com.chan.net.Result result) {

                            }
                        });
                        backgroundHandler.removeMessages(ACTION_CHANNEL_REFRESH);
                        backgroundHandler.sendEmptyMessageDelayed(ACTION_CHANNEL_REFRESH, PROGRAM_DURING);
                        break;
                    case ACTION_PROGRAM_NEXT:
                        mNextProgram = null;
                        Bundle bundle = msg.getData();
                        String url = bundle.getString("data");
                        if (!tvChannels.isEmpty()
                                && !TextUtils.isEmpty(url)) {
                            TvChannel tvChannel = tvChannels.get(_position);
                            List<TvProgram> tvPrograms = new ArrayList<>();
                            tvPrograms.addAll(tvChannel.getTvPrograms());
                            if (!tvPrograms.isEmpty()) {
                                int next = -1;
                                for (int i = 0; i < tvPrograms.size(); i++) {
                                    TvProgram tvProgram = tvPrograms.get(i);
                                    if (tvProgram != null
                                            && !TextUtils.isEmpty(tvProgram.getUrl())) {
                                        if (tvProgram.getUrl().equals(url)) {
                                            next = i + 1;
                                            break;
                                        }
                                    }
                                }
                                if (next > 0 && next < tvPrograms.size()) {
                                    mNextProgram = tvPrograms.get(next);
                                    if (TextUtils.isEmpty(mNextProgram.getUrl())) {
                                        mNextProgram = null;
                                    }
                                }
                            }
                        }
                        break;
                }
                return false;
            }
        });
        AppUtil.flushStackLocalLeaks(backgroundHandler.getLooper());
    }

    @Override
    protected void initData() {
        backgroundHandler.removeMessages(ACTION_CHANNEL_REFRESH);
        Activity activity = AppUtil.getAppCompActivity(mContext);
        PermissionHelper.getInstance().requestLocationPerission(activity, new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                LocationHelper.getInstance().init(mContext, new AMapLocationListener() {

                    @Override
                    public void onLocationChanged(AMapLocation aMapLocation) {
                        if (aMapLocation.getErrorCode() == 0) {
                            String region = aMapLocation.getProvince() + aMapLocation.getCity();
                            LocationHelper.getInstance().setRegion(region);
                            LocationHelper.getInstance().stop();
                            loadData();
                            backgroundHandler.removeMessages(ACTION_CHANNEL_REFRESH);
                            backgroundHandler.sendEmptyMessageDelayed(ACTION_CHANNEL_REFRESH, PROGRAM_DURING);
                        } else {
                            loadData();
                            backgroundHandler.removeMessages(ACTION_CHANNEL_REFRESH);
                            backgroundHandler.sendEmptyMessageDelayed(ACTION_CHANNEL_REFRESH, PROGRAM_DURING);
                        }
                    }
                });
            }
        }, new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                LocationHelper.getInstance().init(mContext, new AMapLocationListener() {
                    @Override
                    public void onLocationChanged(AMapLocation aMapLocation) {
                        if (aMapLocation.getErrorCode() == 0) {
                            String region = aMapLocation.getProvince() + aMapLocation.getCity();
                            LocationHelper.getInstance().setRegion(region);
                            LocationHelper.getInstance().stop();
                            loadData();
                            backgroundHandler.removeMessages(ACTION_CHANNEL_REFRESH);
                            backgroundHandler.sendEmptyMessageDelayed(ACTION_CHANNEL_REFRESH, PROGRAM_DURING);
                        } else {
                            loadData();
                            backgroundHandler.removeMessages(ACTION_CHANNEL_REFRESH);
                            backgroundHandler.sendEmptyMessageDelayed(ACTION_CHANNEL_REFRESH, PROGRAM_DURING);
                        }
                    }
                });
            }
        });
    }

    private void loadData() {
        if (tvChannels.isEmpty()) {
            RxAppCompatActivity activity = (RxAppCompatActivity) AppUtil.getAppCompActivity(mContext);
            requestTvChannelCommand = TVChannelManager.getChannelLives(mContext, activity.<com.chan.net.Result<List<TvChannel>>>bindToLifecycle(), new HttpCallback<List<TvChannel>>() {
                @Override
                public void onSuccess(String requestCommand, com.chan.net.Result<List<TvChannel>> data) {
                    tvChannels.clear();
                    tvChannels.addAll(data.getData());
                    channelAdapter.setNewData(new ArrayList<Object>(data.getData()));
                    String gid = SharePrefUtil.getIjkLiveId(mContext);
                    int k = 0;
                    if (!TextUtils.isEmpty(gid)) {
                        for (int i = 0; i < tvChannels.size(); i++) {
                            TvChannel tvChannel = tvChannels.get(i);
                            if (gid.equals(tvChannel.getGid())) {
                                k = i;
                                break;
                            }
                        }
                    }
                    play(k);
                }

                @Override
                public void onFail(String requestCommand, com.chan.net.Result result) {
                    if (NetworkHelper.getInstance().hasConnection(mContext)) {
                        loadview.netError(view_player);
                    } else {
                        loadview.loadError(view_player);
                    }
                }
            });
        } else {
            String gid = SharePrefUtil.getIjkLiveId(mContext);
            int k = 0;
            if (!TextUtils.isEmpty(gid)) {
                for (int i = 0; i < tvChannels.size(); i++) {
                    TvChannel tvChannel = tvChannels.get(i);
                    if (gid.equals(tvChannel.getGid())) {
                        k = i;
                        break;
                    }
                }
            }
            play(k);
        }
        if (companyList.isEmpty()) {
            requestCompanyVideoCommand = TVChannelManager.getCompanyVods(mContext, AccountHelper.getInstance().getPhone(mContext), this);
        }
    }

    private void loadTvPrograms(TvChannel tvChannel) {
        mDataHandler.removeMessages(actionReviewVodCommand);
        if (!TextUtils.isEmpty(requestReviewVodCommand)) {
            CustomOkHttpClient.cancleAll(requestReviewVodCommand);
        }
        if (tvChannel.getTvPrograms().isEmpty()) {
            requestReviewVodCommand = TVChannelManager.getReviewVods(mContext, tvChannel.getGid(), "", this);
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
            for (int i = 0; i < tvChannel.getTvPrograms().size(); i++) {
                TvProgram tvProgram = tvChannel.getTvPrograms().get(i);
                try {
                    // 正在播放的节目
                    if (!TextUtils.isEmpty(tvProgram.getTime())) {
                        Date date = dateFormat.parse(tvProgram.getTime());
                        if (date.getTime() <= System.currentTimeMillis()) {
                            if ((i + 1) < tvChannel.getTvPrograms().size()) {
                                Object object1 = tvChannel.getTvPrograms().get(i + 1);
                                TvProgram tvProgram1 = (TvProgram) object1;
                                if (tvProgram1.getTime() != null) {
                                    Date date1 = dateFormat.parse(tvProgram1.getTime());
                                    if (date1.getTime() > System.currentTimeMillis()) {
                                        tvChannel.setPlayingProgram(tvProgram);
                                    }
                                }
                            } else {
                                if (date.getTime() < System.currentTimeMillis()) {
                                    String t1 = TimeUtil.getFormat2Time(date.getTime());
                                    String t2 = TimeUtil.getFormat2Time(System.currentTimeMillis());
                                    if (TextUtils.isEmpty(tvProgram.getUrl()) && t1.equals(t2)) {
                                        tvChannel.setPlayingProgram(tvProgram);
                                    }
                                } else if (date.getTime() == System.currentTimeMillis()) {
                                    tvChannel.setPlayingProgram(tvProgram);
                                }
                            }
                        }
                    }
                } catch (ParseException e) {

                }
            }
            channelAdapter.notifyItemChanged(_position, tvChannels.get(_position));
            pcv_home.setProgramSeek(tvChannels.get(_position).getTvPrograms());
            pcv_home.refreshProgramSeek();
        }
    }

    @Override
    public boolean isLive() {
        return _isLive;
    }

    @Override
    public boolean isAdvert() {
        return _isAdvert;
    }

    @Override
    public boolean isShift() {
        return _isShift;
    }

    @Override
    public boolean isAudio() {
        return _isAudio;
    }

    @Override
    public boolean isClip() {
        return _isClip;
    }

    @Override
    protected boolean isHasFragment() {
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        Fragment search = DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), "search");
        if (search != null && search.isVisible()) {
            return true;
        }
        Fragment mine = DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), "mineFragment");
        if (mine != null && mine.isVisible()) {
            return true;
        }
        Fragment company = DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), TVCompanyViewController.tag());
        if (company != null && company.isVisible()) {
            return true;
        }
        return super.isHasFragment();
    }

    @Override
    protected void openProgram() {
        if (!tvChannels.isEmpty()) {
            final TvChannel tvChannel = tvChannels.get(_position);
            if (!tvChannel.getDatePrograms().isEmpty()) {
                super.openProgram();
                AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
                TVProgramsViewController programsViewController = TVProgramsViewController.newInstance();
                programsViewController.setData(tvChannel.getDatePrograms(), tvChannel.getTvPrograms(), tvChannel.getName(), tvChannel.getGid(), _isLive, mTvProgram);
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), programsViewController, TVProgramsViewController.class.getName());
            } else {
                backgroundHandler.removeMessages(ACTION_PROGRAM_REFRESH);
                backgroundHandler.sendEmptyMessage(ACTION_PROGRAM_REFRESH);
                ToastUtil.show(mContext, "节目加载中，请稍等");
            }
        }
    }

    @Override
    protected void backLive() {
        if (!isLive()) {
            // 手动隐藏广告
            if (mTvProgram != null && mNfwxVideoPlayer.getDuration() != 0 && AccountHelper.getInstance().isLogin(mContext)) {
                long tvProgramPosition = mNfwxVideoPlayer.getCurrentPosition();
                int tvProgramPresent = (int) ((mNfwxVideoPlayer.getCurrentPosition() * 100) / mNfwxVideoPlayer.getDuration());
                WatchRecordManager.requestAddViewHistroy(mContext, mTvProgram.getProgram_id(), tvProgramPosition, tvProgramPresent, null);
            }
            NfwxVideoPlayerManager.instance().suspendVideoPlayer();
            refreshView(false);
            if (events != null && events.getFragment() != -1) {
                final PlayEvents playEvents = events;
                events = null;
                _isLive = true;
                onShot = "";
                AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
                if (playEvents.getFragment() == PlayEvents.SEARCH) {
                    SearchFragment searchFragment = SearchFragment.newInstance();
                    searchFragment.loadResultData(playEvents.getKeyword());
                    DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), searchFragment, playEvents.getTag());
                } else if (playEvents.getFragment() == PlayEvents.MINE) {
                    MineFragment mineFragment = MineFragment.newInstance();
                    //mineFragment.setOnEventListener(this);
                    mineFragment.loadResultData(playEvents.getMePosition());
                    DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), mineFragment, playEvents.getTag());
                }
            } else if (_isCompany) {
                _isCompany = false;
                _isLive = true;
                AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
                TVCompanyViewController companyDialogFragment = TVCompanyViewController.newInstance((ArrayList<Company>) companyList);
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), companyDialogFragment, TVCompanyViewController.tag());
                reStart();
            } else {
                ThreadHelper.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshView(true);
                        ll_bottom.setVisibility(View.VISIBLE);
                        pcv_home.showTvprogram();
                        tv_vodplayer_back.setText("直播");
                        mTvProgram = null;
                        _isLive = true;
                        _isHandPause = false;
                        if (_isHotDialog) {
                            if (!tvChannels.isEmpty()) {
                                openTvHotDialog(1);
                            }
                            _isHotDialog = false;
                        }
                        reStart();
                    }
                }, durationMillis + 100);
            }
        }
    }

    @Override
    protected boolean isDownedPlay() {
        return _isDownLoaded;
    }

    @Override
    protected void download() {
        if (mTvProgram != null && !TextUtils.isEmpty(mTvProgram.getUrl())) {
            // 回看更新下载ui
            if (!AccountHelper.getInstance().isLogin(mContext)) {
                ToastUtil.show(mContext, "用户未登录", Toast.LENGTH_LONG);
                return;
            }
            if (!NetworkHelper.getInstance().hasConnection(mContext)) {
                ToastUtil.show(mContext, R.string.nointernet, Toast.LENGTH_LONG);
                return;
            }
            if (NetworkHelper.getInstance().isConnection4g(mContext)
                    && !SharePrefUtil.getDownloadChoose(mContext)) {
                ToastUtil.show(mContext, R.string.download_4g, Toast.LENGTH_LONG);
                return;
            }
            DownProgramDao dao = AppDatabase.getInstance(mContext).programDao();
            List<DownProgramModel> downProgramModels = dao.queryAllByUrl(mTvProgram.getUrl());
            if (downProgramModels.isEmpty()) {
                RxAppCompatActivity activity = (RxAppCompatActivity) AppUtil.getAppCompActivity(mContext);
                DownloadM3u8Controller.getInstance().download(mContext, mTvProgram, activity.<Integer>bindToLifecycle(), new ValueCallback<Integer>() {
                    @Override
                    public void onReceiveValue(final Integer value) {
                        if (value == DownProgramModel.STATS_FAIL) {
                            ToastUtil.show(mContext, "下载失败");
                        } else if (value == DownProgramModel.STATS_DOWNLOADED) {
                            ToastUtil.show(mContext, "已正在下载");
                        } else {
                            ToastUtil.show(mContext, "正在下载");
                        }
                    }
                });
            } else {
                DownProgramModel downProgramModel = downProgramModels.get(0);
                if (downProgramModel.getStats() == DownProgramModel.STATS_PAUSE) {
                    DownloadM3u8Controller.getInstance().start(mContext, mTvProgram.getUrl());
                    ToastUtil.show(mContext, "正在下载");
                } else {
                    ToastUtil.show(mContext, "正在下载中");
                }
            }
        }
    }

    @Override
    protected void share() {
        super.share();
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        ReviewShareDialogFragment shareDialogFragment = ReviewShareDialogFragment.newInstance(true);
        shareDialogFragment.setOnShareClickListener(new ReviewShareDialogFragment.OnShareClickListener() {
            @Override
            public void pengy() {
                share2WeiXin(SendMessageToWX.Req.WXSceneTimeline);
            }

            @Override
            public void weix() {
                share2WeiXin(SendMessageToWX.Req.WXSceneSession);
            }

            /**
             * 分享
             * @param wxSceneSession
             */
            private void share2WeiXin(final int wxSceneSession) {
                if (NFWXApplication.getInstance().getIwxapi().isWXAppInstalled()) {
                    String filename;
                    String gid;
                    String videoPath = onShot;
                    String bitmapUrl = UrlHelper.getShareThumbUrl();
                    if (videoPath.contains(".m3u8")) {
                        bitmapUrl = onShot.replace(".m3u8", ".jpg");
                        int lastIndex = videoPath.lastIndexOf(".m3u8");
                        if (lastIndex != -1) {
                            String path = videoPath.substring(0, lastIndex);
                            lastIndex = path.lastIndexOf("/");
                            if (lastIndex != -1) {
                                filename = path.substring(lastIndex + 1);
                                path = path.substring(0, lastIndex);
                                lastIndex = path.lastIndexOf("/");
                                if (lastIndex != -1) {
                                    gid = path.substring(lastIndex + 1);
                                    videoPath = UrlHelper.getShareVideoUrl(gid, filename);
                                }
                            }
                        }
                    }
                    final String finalVideoPath = videoPath;
                    GlideUtil.downloadImage(NFWXApplication.getInstance(), bitmapUrl, new ValueCallback<File>() {
                        @Override
                        public void onReceiveValue(File value) {
                            if (value == null) {
                                GlideUtil.downloadImage(NFWXApplication.getInstance(), UrlHelper.getShareThumbUrl(), new ValueCallback<File>() {
                                    @Override
                                    public void onReceiveValue(File value) {
                                        if (value == null) {
                                            return;
                                        }
                                        String liveingName = title_channel_name.getText().toString();
                                        String des = "我用" + mContext.getString(R.string.app_name) + "APP给你截了一段精彩视频:" + liveingName;
                                        try {
                                            AppUtil.shareWebPage2WeiXin(getContext(), wxSceneSession, finalVideoPath, liveingName, des, BitmapFactory.decodeStream(new FileInputStream(value)));
                                        } catch (FileNotFoundException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                                return;
                            }
                            String liveingName = title_channel_name.getText().toString();
                            String des = "我用" + mContext.getString(R.string.app_name) + "APP给你截了一段精彩视频:" + liveingName;
                            try {
                                AppUtil.shareWebPage2WeiXin(getContext(), wxSceneSession, finalVideoPath, liveingName, des, BitmapFactory.decodeStream(new FileInputStream(value)));
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else {
                    ToastUtil.show(getContext(), "没有安装微信");
                }
            }
        });
        DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), shareDialogFragment);
    }

    @Override
    protected void openCompany() {
        super.openCompany();
        CcpActivity.startActivity(mContext);
//        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
//        TVCompanyViewController companyDialogFragment = TVCompanyViewController.newInstance((ArrayList<Company>) companyList);
//        DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), companyDialogFragment, TVCompanyViewController.tag());
//        NfwxVideoPlayerManager.instance().suspendVideoPlayer();
//        _isHandPause = true;
    }

    @Override
    protected void openSearch() {
        super.openSearch();
        SearchFragment searchFragment = SearchFragment.newInstance();
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), searchFragment, "search");
        NfwxVideoPlayerManager.instance().suspendVideoPlayer();
        _isHandPause = true;
    }

    @Override
    protected void openHotLives() {
        if (!tvChannels.isEmpty()) {
            super.openHotLives();
            openTvHotDialog(0);
        }
    }

    private void openTvHotDialog(int position) {
        TVHotViewController hotViewController = TVHotViewController.newInstance();
        hotViewController.setData(tvChannels, position);
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), hotViewController, "fire");
    }

    @Override
    protected void openMine() {
        super.openMine();
        MineFragment mineFragment = MineFragment.newInstance();
        //mineFragment.setOnEventListener(this);
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), mineFragment, "mineFragment");
        NfwxVideoPlayerManager.instance().suspendVideoPlayer();
        _isHandPause = true;
    }

    @Override
    protected void openclip() {
        if (tvChannels.isEmpty()) {
            return;
        }
        _isShift = true;
        super.openclip();
        MobAgentUtil.cutClicked(mContext);
        cutBeginTime = System.currentTimeMillis();
        TvChannel tvChannel = tvChannels.get(_position);
        if (tvChannel != null && mNfwxVideoPlayer.isPlaying()) {
            refreshClip(true);
            // 设置进度为剪切监听
            pcv_home.clipPause();
            AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
            tvc_controller.requestLiveClipsnap(activity.getSupportFragmentManager(), tvChannel.getGid());
        }
    }

    @Override
    protected void cancelclip() {
        super.cancelclip();
        _isShift = false;
        pcv_home.hiddenBubble();
        refreshClip(false);
        tvc_controller.cancel();
        if (_isnetworkError) {
            mNfwxVideoPlayer.releasePlayer();
            reStart();
        } else {
            pcv_home.clipResume();
        }
        if (cutBeginTime != -1) {
            MobAgentUtil.cutDurations(mContext, cutBeginTime);
            cutBeginTime = -1;
        }
    }

    @Override
    protected void sureclip() {
        if (tvChannels.isEmpty()) {
            return;
        }
        super.sureclip();
        TvChannel tvChannel = tvChannels.get(_position);
        String liveingName = tvChannel.getName() + "--" + tvChannel.getProgram_name();
        tvc_controller.sure();
        String startTime = tvc_controller.getStartTimeUrl();
        String endTime = tvc_controller.getEndTimeUrl();
        String gid = tvChannel.getGid();
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        ShortVideoShareViewController shortVideoShareViewController = ShortVideoShareViewController.newInstance();
        shortVideoShareViewController.setData(gid, startTime, endTime, liveingName);
        shortVideoShareViewController.requestVideoPath(activity.getSupportFragmentManager(), gid, startTime, endTime);
        DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), shortVideoShareViewController);
    }

    @Override
    protected void updateProgress() {
        super.updateProgress();
    }

    @Override
    protected void sure4gplay() {
        super.sure4gplay();
        _isnetworkError = false;
        _isHandPause = false;
        reStart();
    }

    @Override
    public void setShift(boolean isShift) {
        _isShift = isShift;
    }

    @Override
    protected String getGid() {
        if (TextUtils.isEmpty(gid)) {
            return super.getGid();
        }
        return gid;
    }

    private void play(TvProgram tvProgram) {
        if (!TextUtils.isEmpty(tvProgram.getUrl())) {
            if (mTvProgram != null && mNfwxVideoPlayer.getDuration() != 0 && AccountHelper.getInstance().isLogin(mContext)) {
                long tvProgramPosition = mNfwxVideoPlayer.getCurrentPosition();
                int tvProgramPresent = (int) ((mNfwxVideoPlayer.getCurrentPosition() * 100) / mNfwxVideoPlayer.getDuration());
                WatchRecordManager.requestAddViewHistroy(mContext, mTvProgram.getProgram_id(), tvProgramPosition, tvProgramPresent, null);
            }
            if (_isHotDialog) {
                gid = "";
            }
            mTvProgram = tvProgram;
            _isAudio = false;
            _isLive = false;
            _isShift = false;
            findView(R.id.clip_btn).setVisibility(View.VISIBLE);
            findView(R.id.download_btn).setVisibility(View.GONE);
            findView(R.id.share_btn).setVisibility(View.GONE);
            findView(R.id.review_btn).setVisibility(GONE);
            title_channel_name.setText(mTvProgram.getProgram_name());
            if (_isHotDialog) {
                tv_vodplayer_back.setText("返回");
            } else {
                tv_vodplayer_back.setText("直播");
            }
            doPlayVideo(mTvProgram.getUrl());
        }
    }

    private void play(int position) {
        if (mContext == null) {
            return;
        }
        if (_position != position && !tvChannels.isEmpty()) {
            if (_position != -1) {
                CustomOkHttpClient.cancleAll(requestReviewVodCommand);
            }
            mTvProgram = null;
            _position = position;
            _isLive = true;
            _isShift = false;

            final TvChannel channel = tvChannels.get(position);
            // 初始化进度条
            gid = channel.getGid();
            SharePrefUtil.saveIjkLiveId(mContext, channel.getGid());

            title_channel_name.setText(channel.getName());

            MobAgentUtil.selectedChannel(mContext, channel.getName());

            channelAdapter.setSelected(position);
            recyclerViewHelper.smoothScrollToPositionCenter(position);
            channelAdapter.notifyDataSetChanged();
            autoActionHidden();
            qrv_review.clearDate();
            qrv_review.clearPrograms();
            pcv_home.clearProgram();
            loadTvPrograms(channel);
//            channel.loadPrograms(mContext, new ValueCallback<List<TvProgram>>() {
//                @Override
//                public void onReceiveValue(final List<TvProgram> value) {
//                    channelAdapter.notifyItemChanged(_position, channel);
//                    pcv_home.setProgramSeek(value);
//                    pcv_home.refreshProgramSeek();
//                }
//            });
            // 启动program定时刷新
            backgroundHandler.removeMessages(ACTION_PROGRAM_REFRESH);
            backgroundHandler.sendEmptyMessageDelayed(ACTION_PROGRAM_REFRESH, PROGRAM_DURING);

            findView(R.id.clip_btn).setVisibility(View.GONE);
            findView(R.id.review_btn).setVisibility(GONE);
            findView(R.id.download_btn).setVisibility(View.VISIBLE);
            findView(R.id.share_btn).setVisibility(View.VISIBLE);
            if (channel.isPure_audio()) {
                _isAudio = true;
                // 适配问题，分开原图和倒影图片
                GlideUtil.loadOnlyReflectedImage(mContext, channel.getLogo(), iv_audio_reflected, R.dimen.dp5);
                GlideUtil.loadForgoundImage(mContext, channel.getLogo(), iv_audio_img, R.dimen.dp5);
            } else {
                _isAudio = false;
            }
            doPlayVideo(channel.getUrl());
            preChannelName = channel.getName();
            fromState = FROM_NONE;
        }
    }

    private void play(String path, int position, String name) {
        gid = "";
        title_channel_name.setText(name);
        _isLive = false;
        _isShift = false;
        pcv_home.hideTvprogram();
        refreshView(true);
        autoActionHidden();
        doPlayVideo(path, position);
    }

    private void doPlayVideo(String path) {
        doPlayVideo(path, 0);
    }

    private void doPlayVideo(String path, long position) {
        if (path.contains(".jpg") || path.contains(".png")) {
            _isPic = true;
            hideLoading();
            loadview.removeParentView(view_player);
            findView(R.id.clip_btn).setVisibility(View.GONE);
            findView(R.id.download_btn).setVisibility(View.GONE);
            findView(R.id.share_btn).setVisibility(View.GONE);
            pcv_home.setVisibility(View.VISIBLE);
            pcv_home.reset();
            pcv_home.clearProgramSeek();
            pcv_home.stopView();
            NfwxVideoPlayerManager.instance().suspendVideoPlayer();
            GlideUtil.loadImage(mContext, path, iv_player_thumb);
            iv_player_thumb.setVisibility(View.VISIBLE);
            mNfwxVideoPlayer.releasePlayer();
        } else {
            if (path.contains("http")) {
                _isDownLoaded = false;
            } else {
                _isDownLoaded = true;
            }
            if (TextUtils.isEmpty(AccountHelper.getInstance().getIp()) && !isDownedPlay()) {
                final String finalPath = path;
                final long finalPosition = position;
                AccountHelper.getInstance().requestIp(mContext, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
                            doPlayVideo(finalPath, finalPosition);
                        } else {
                            ThreadHelper.post(new Runnable() {
                                @Override
                                public void run() {
                                    doPlayVideo(finalPath, finalPosition);
                                }
                            });
                        }
                    }
                });
                return;
            }
            _isPic = false;
            iv_player_thumb.setVisibility(View.GONE);
            iv_player_thumb.setImageDrawable(null);
            if (!path.equals(onShot)) {
                onShot = path;
                if (!_isDownLoaded) {
                    path = UrlHelper.getIjkLivePath(path);
                }
                changeLiveView();
                pcv_home.reset();
                if (isLive()) {
                    if (isAudio()) {
                        findView(R.id.clip_btn).setVisibility(View.GONE);
                        findView(R.id.download_btn).setVisibility(View.GONE);
                        findView(R.id.share_btn).setVisibility(View.GONE);
                        pcv_home.setVisibility(View.GONE);
                    } else {
                        pcv_home.setVisibility(View.VISIBLE);
                        pcv_home.showTvprogram();
                        findView(R.id.clip_btn).setVisibility(View.VISIBLE);
                        findView(R.id.download_btn).setVisibility(View.GONE);
                        findView(R.id.share_btn).setVisibility(View.GONE);
                    }
                    ll_titlebar.setVisibility(View.VISIBLE);
                    // 友盟统计频道
                    if (playBeginTime != -1 && !TextUtils.isEmpty(preChannelName)) {
                        MobAgentUtil.channelDurations(mContext, preChannelName, playBeginTime);
                        playBeginTime = -1;
                        preChannelName = "";
                    }
                    playBeginTime = System.currentTimeMillis();
                } else {
                    // 友盟统计频道
                    if (playBeginTime != -1 && !TextUtils.isEmpty(preChannelName)) {
                        MobAgentUtil.channelDurations(mContext, preChannelName, playBeginTime);
                        playBeginTime = -1;
                        preChannelName = "";
                    }
                    if (isDownedPlay() || _isCompany) {
                        findView(R.id.download_btn).setVisibility(View.GONE);
                        findView(R.id.share_btn).setVisibility(View.GONE);

                    } else {
                        findView(R.id.download_btn).setVisibility(View.VISIBLE);
                        findView(R.id.share_btn).setVisibility(View.VISIBLE);
                    }
                    findView(R.id.clip_btn).setVisibility(View.GONE);
                    ll_titlebar.setVisibility(View.GONE);
                }
                findView(R.id.iv_advertise).setVisibility(View.GONE);
                if (!ActivityHelper.getInstance().isBackground()
                        && NetworkHelper.getInstance().hasConnection(mContext)) {
                    if (!isDownedPlay() && NetworkHelper.getInstance().isConnection4g(mContext)) {
                        if (!SharePrefUtil.get4gstautus(mContext)) {
                            mNfwxVideoPlayer.releasePlayer();
                            loadview.removeParentView(view_player);
                            loadview.net4gError(view_player);
                            return;
                        }
                    }
                } else if (!isDownedPlay()) {
                    if (!NetworkHelper.getInstance().hasConnection(mContext)) {
                        mNfwxVideoPlayer.releasePlayer();
                        loadview.netError(view_player);
                    }
                    return;
                }
                mNfwxVideoPlayer.releasePlayer();
                mNfwxVideoPlayer.setUp(path, null);
                if (position == 0) {
                    mNfwxVideoPlayer.start();
                } else {
                    mNfwxVideoPlayer.start(position);
                }
                playView();
            }
        }
    }

    @Override
    public String getTimesShiftUrl(long timeCode) {
        if (tvChannels.isEmpty() || _position == -1) {
            return "";
        }
        _isShift = true;
        TvChannel tvChannel = tvChannels.get(_position);
        String path = UrlHelper.getTimesShiftUrl(tvChannel.getGid(), timeCode);
        path = UrlHelper.getIjkLivePath(path);
        return path;
    }

    @Override
    public void reStart() {
        if (_isHandPause) {
            return;
        }
        if (isLive()) {
            onShot = "";
            if (tvChannels.isEmpty()) {
                loadData();
            } else {
                if (isShift()) {
                    long timecode = mNfwxVideoPlayer.getTimeCode();
                    if (timecode > 1453109317) { // 大于1970年1月1日
                        mNfwxVideoPlayer.seekByTimeCode(timecode);
                    } else {
                        final int i = _position;
                        _position = -1;
                        play(i);
                    }
                } else {
                    final int i = _position;
                    _position = -1;
                    play(i);
                }
            }
        } else {
            final String path = onShot;
            onShot = "";
            if (mNfwxVideoPlayer.getCurrentPosition() >= (mNfwxVideoPlayer.getDuration() - 10000)) {
                doPlayVideo(path);
            } else {
                doPlayVideo(path, mNfwxVideoPlayer.getCurrentPosition());
            }
        }
    }

    @Override
    public void onFailure(Call call, final IOException e) {
        String requestCommand = (String) call.request().tag();
        if (requestCommand.equals(requestTvChannelCommand)) {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    if (NetworkHelper.getInstance().hasConnection(mContext)) {
                        loadview.netError(view_player);
                    } else {
                        loadview.loadError(view_player);
                    }
                }
            });
        } else if (requestCommand.equals(requestTvChannelRefreshCommand)) {

        }
    }

    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        String requestCommand = (String) call.request().tag();
        if (requestCommand.equals(requestTvChannelCommand)) {
            if (response.code() == 200 && response.isSuccessful()) {
                final String str = response.body().string();
                SharePrefUtil.saveLiveStr(mContext, str);
                ThreadHelper.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            final Result<List<TvChannel>> result = JSON.parseObject(str, new TypeToken<Result<List<TvChannel>>>() {
                            }.getType());
                            if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                                tvChannels.clear();
                                tvChannels.addAll(result.getData());
                                channelAdapter.setNewData(new ArrayList<Object>(result.getData()));
                                String gid = SharePrefUtil.getIjkLiveId(mContext);
                                int k = 0;
                                if (!TextUtils.isEmpty(gid)) {
                                    for (int i = 0; i < tvChannels.size(); i++) {
                                        TvChannel tvChannel = tvChannels.get(i);
                                        if (gid.equals(tvChannel.getGid())) {
                                            k = i;
                                            break;
                                        }
                                    }
                                }
                                play(k);
                            }
                        } catch (Exception e) {

                        }
                    }
                });
            } else {
                ThreadHelper.post(new Runnable() {
                    @Override
                    public void run() {
                        loadview.removeParentView(view_player);
                    }
                });
            }
        } else if (requestCommand.equals(requestTvChannelRefreshCommand)) {
            if (response.code() == 200 && response.isSuccessful()) {
                String str = response.body().string();
                try {
                    final Result<List<TvChannel>> result = JSON.parseObject(str, new TypeReference<Result<List<TvChannel>>>() {
                    }.getType());
                    if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                        String liveStr = SharePrefUtil.getLivestr(mContext);
                        if (!liveStr.equals(str)) {
                            SharePrefUtil.saveLiveStr(mContext, str);
                            mDataHandler.removeMessages(actionChannelRefreshCommand);
                            Message message = mDataHandler.obtainMessage(actionChannelRefreshCommand);
                            Bundle bundle = new Bundle();
                            bundle.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) result.getData());
                            message.setData(bundle);
                            mDataHandler.sendMessage(message);
                        }
                    }
                } catch (Exception e) {

                }

            }
        } else if (requestCommand.equals(requestReviewVodCommand)) {
            if (response.code() == 200 && response.isSuccessful()) {
                final String str = response.body().string();
                try {
                    RxAppCompatActivity appCompatActivity = (RxAppCompatActivity) AppUtil.getAppCompActivity(mContext);
                    Observable.create(new ObservableOnSubscribe<List<TvProgram>>() {
                        @Override
                        public void subscribe(ObservableEmitter<List<TvProgram>> e) throws Exception {
                            final Result<List<TvProgram>> result = JSON.parseObject(str, new TypeReference<Result<List<TvProgram>>>() {
                            }.getType());
                            boolean isInit = true;
                            if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                                sortData(result.getData());
                                List<TvProgram> mList = new ArrayList(result.getData());
                                tvChannels.get(_position).setTvPrograms(mList);
                                List<String> MMdds = new ArrayList<String>();
                                Map<String, List<TvProgram>> map = new HashMap<>();
                                for (int i = 0; i < mList.size(); i++) {
                                    TvProgram tvProgram = mList.get(i);
                                    tvProgram.setPlaying(false);
                                    if (tvProgram.getType() == 1) {
                                        tvProgram.setPlaying(true);
                                    }
                                    // 正在播放的节目
                                    if (isInit) {
                                        Date date = dateFormat.parse(tvProgram.getTime());
                                        if (date.getTime() <= System.currentTimeMillis()) {
                                            if ((i + 1) < mList.size()) {
                                                Object object1 = mList.get(i + 1);
                                                TvProgram tvProgram1 = (TvProgram) object1;
                                                Date date1 = dateFormat.parse(tvProgram1.getTime());
                                                if (date1.getTime() > System.currentTimeMillis()) {
                                                    tvChannels.get(_position).setPlayingProgram(tvProgram);
                                                    isInit = false;
                                                }
                                            } else {
                                                if (date.getTime() < System.currentTimeMillis()) {
                                                    String t1 = TimeUtil.getFormat2Time(date.getTime());
                                                    String t2 = TimeUtil.getFormat2Time(System.currentTimeMillis());
                                                    if (TextUtils.isEmpty(tvProgram.getUrl()) && t1.equals(t2)) {
                                                        tvChannels.get(_position).setPlayingProgram(tvProgram);
                                                        isInit = false;
                                                    }
                                                } else if (date.getTime() == System.currentTimeMillis()) {
                                                    tvChannels.get(_position).setPlayingProgram(tvProgram);
                                                    isInit = false;
                                                }
                                            }
                                        }
                                    }

                                    if (!TextUtils.isEmpty(tvProgram.getTime())) {
                                        Date date = dateFormat.parse(tvProgram.getTime());
                                        String MMdd = TimeUtil.getFormatYYMMddTime((date.getTime() / 1000L));
                                        if (map.containsKey(MMdd)) {
                                            List<TvProgram> list = map.get(MMdd);
                                            list.add(tvProgram);
                                        } else {
                                            MMdds.add(MMdd);
                                            List<TvProgram> list = new ArrayList<>();
                                            list.add(tvProgram);
                                            map.put(MMdd, list);
                                        }
                                    }
                                }
                                for (String key : map.keySet()) {
                                    DateProgram dateProgram = new DateProgram();
                                    dateProgram.setDate(key);
                                    dateProgram.setTvPrograms(map.get(key));
                                    tvChannels.get(_position).getDatePrograms().add(dateProgram);
                                }
                                e.onNext(mList);
                            }
                            e.onComplete();
                        }
                    }).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .compose(appCompatActivity.<List<TvProgram>>bindToLifecycle())
                            .subscribe(new Observer<List<TvProgram>>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(List<TvProgram> tvPrograms) {
                                    channelAdapter.notifyItemChanged(_position, tvChannels.get(_position));
                                    pcv_home.setProgramSeek(tvPrograms);
                                    pcv_home.refreshProgramSeek();
                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                } catch (Exception e) {

                }
            }
        }
    }

    /**
     * 下一个节目
     */
    @Override
    public void playBack() {
        if (isClip() || _isLock) {
            return;
        }
        refreshView(true);
        autoActionHidden();
        if (isLive()) {
            if (_position == 0) {
                if (tvChannels.isEmpty()) {
                    return;
                }
                play(tvChannels.size() - 1);
            } else {
                play(_position - 1);
            }
        }
    }

    /**
     * 上一个节目
     */
    @Override
    public void playNext() {
        if (isClip() || _isLock) {
            return;
        }
        refreshView(true);
        autoActionHidden();
        if (isLive()) {
            if (tvChannels.isEmpty()) {
                play(0);
                return;
            }
            if (_position == tvChannels.size() - 1) {
                play(0);
            } else {
                play(_position + 1);
            }
        }
    }

    @Override
    public void playEventBus(PlayEvents events) {
        super.playEventBus(events);
        this.events = events;
        if (events.getFragment() != -1) {
            tv_vodplayer_back.setText("返回");
        } else {
            tv_vodplayer_back.setText("直播");
        }
        final String path = events.getPath();
        final String programName = events.getName();
        final int position = events.getPosition();
        if (0 < events.getProgramId()) {
            mTvProgram = new TvProgram();
            mTvProgram.setProgram_id(events.getProgramId());
            mTvProgram.setUrl(path);
            mTvProgram.setProgram_name(programName);
        } else {
            mTvProgram = null;
        }
        RxAppCompatActivity appCompatActivity = (RxAppCompatActivity) AppUtil.getAppCompActivity(mContext);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) {
                DownProgramDao dao = AppDatabase.getInstance(mContext).programDao();
                List<DownProgramModel> downProgramModels = dao.queryAllByUrl(path);
                if (downProgramModels.isEmpty()) {
                    e.onNext(path);
                } else {
                    DownProgramModel downProgramModel = downProgramModels.get(0);
                    if (downProgramModel.getStats() == DownProgramModel.STATS_SUCCESS) {
                        e.onNext(downProgramModel.getLocalPath());
                    } else {
                        e.onNext(path);
                    }
                }
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(appCompatActivity.<String>bindToLifecycle())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        play(s, position, programName);
                        fromState = FROM_OTHERS;
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 预约
     *
     * @param event
     */
    @Override
    public void appiontEvent(AppointEvent event) {
        if (event == null || event.getMap() == null || tvChannels.isEmpty()) {
            return;
        }
        BaseDialogFragment dialogFragment = null;
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        View view = findView(R.id.content);
        List<Fragment> fragments = activity.getSupportFragmentManager().getFragments();
        if (!fragments.isEmpty()) {
            final Fragment fragment = fragments.get(fragments.size() - 1);
            if (fragment instanceof BaseDialogFragment) {
                if (fragment.isVisible()) {
                    dialogFragment = (BaseDialogFragment) fragment;
                    view = dialogFragment.getView();
                }
            }
        }
        final Map<String, String> appiont = event.getMap();
        // 预约节目是否已经结束
        String actionText = activity.getString(R.string.appiontment_look);
        String text = activity.getString(R.string.appiontment_note, appiont.get("program_name"));

        // 预约节目结束跳转至我的预约界面反则查看对应的直播
        final BaseDialogFragment finalDialogFragment = dialogFragment;
        TSnackbarUtil.showTSnackbar(view, text, actionText, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tvChannels.isEmpty()) {
                    for (int i = 0; i < tvChannels.size(); i++) {
                        TvChannel tvChannel = tvChannels.get(i);
                        if (tvChannel.getGid().equals(appiont.get("gid"))) {
                            if (finalDialogFragment != null) {
                                finalDialogFragment.dismissAllowingStateLoss();
                            }
                            play(i);
                            break;
                        }
                    }
                }
            }
        });
    }

    @Override
    public boolean handleMessage(Message msg) {
        super.handleMessage(msg);

        return false;
    }

    @Override
    protected boolean isPic() {
        return _isPic;
    }

    @Override
    protected void scanWifi() {
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        PermissionHelper.getInstance().requestWifiPerission(activity, new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                if (!WifiSupport.isOpenWifi(mContext)) {
                    WifiSupport.openWifi(mContext, new WifiSupport.OnWiFiListener() {
                        @Override
                        public void onWiFiAvailable() {
                            //弹出需要切换场景弹框
                            inAir();
                        }

                        @Override
                        public void wifiNoEnable() {

                        }
                    });
                } else {
                    inAir();
                }
            }
        }, new Action<List<String>>() {
            @Override
            public void onAction(List<String> deniedPermissions) {
                if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                    AppCompatActivity activity1 = AppUtil.getAppCompActivity(mContext);
                    PermissionHelper.getInstance().showWifiLocationSettingDialog(activity1);
                }
            }
        });
    }

    private void inAir() {
        //弹出需要切换场景弹框
        SceneChooseController sceneChooseController = SceneChooseController.newInstance();
        sceneChooseController.setOnAriPortClickListener(new SceneChooseController.OnAriPortClickListener() {
            @Override
            public void onClick(View view) {
                tryagain();
            }
        });
        sceneChooseController.setOnBusClickListener(new SceneChooseController.OnBusClickListener() {
            @Override
            public void onClick(View view) {
                //scanBusWifi();
            }
        });
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), sceneChooseController, "busscene");
    }

    public void scanBusWifi() {
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        if (NetworkHelper.getInstance().isConnection4g(mContext)
                || !WifiSupport.getConnectedWifiInfo(mContext).getSSID().contains("广州公交免费wifi")) {
            WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), "wifinote");
            if (fragment == null) {
                WifiNoteFragment wifiNoteFragment = WifiNoteFragment.newInstance(1);
                wifiNoteFragment.setOnWifiNoteClick(new WifiNoteFragment.onWifiNoteClick() {
                    @Override
                    public void tryagain() {
                        //scanBusWifi();
                    }
                });
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiNoteFragment, "wifinote");
            } else {
                fragment.setOnWifiNoteClick(new WifiNoteFragment.onWifiNoteClick() {
                    @Override
                    public void tryagain() {
                        scanBusWifi();
                    }
                });
                fragment.loadLoading();
            }
            ThreadHelper.postDelayed(new Runnable() {
                @Override
                public void run() {
                    WifiSupport.scanBusWifi(mContext, new WifiSupport.OnScanBusWifiFinishListener() {
                        @Override
                        public void onHasWifi() {
                            AppCompatActivity activity1 = AppUtil.getAppCompActivity(mContext);
                            DialogFragmentHelper.removeFragment(activity1.getSupportFragmentManager(), "wifinote");
                            WifiSupport.connectBusWifi(mContext);
                        }

                        @Override
                        public void onNone() {
                            AppCompatActivity activity1 = AppUtil.getAppCompActivity(mContext);
                            if (NetworkHelper.getInstance().isConnection4g(mContext)) {
                                WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(activity1.getSupportFragmentManager(), "wifinote");
                                if (fragment == null) {
                                    WifiNoteFragment wifiNoteFragment = WifiNoteFragment.newInstance(2);
                                    wifiNoteFragment.setOnWifiNoteClick(new WifiNoteFragment.onWifiNoteClick() {
                                        @Override
                                        public void tryagain() {
                                            //scanBusWifi();
                                        }
                                    });
                                    DialogFragmentHelper.showDialogFragment(activity1.getSupportFragmentManager(), wifiNoteFragment, "wifinote");
                                } else {
                                    fragment.loadFailure();
                                }
                            } else {
                                WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(activity1.getSupportFragmentManager(), "wifinote");
                                if (fragment != null) {
                                    fragment.dismissAllowingStateLoss();
                                }
                            }
                        }
                    });
                }
            }, 1000);
        } else {
            WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), "wifinote");
            if (fragment != null) {
                fragment.dismissAllowingStateLoss();
            }
        }
    }

    @Override
    public void tryagain() {
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), "wifinote");
        if (fragment == null) {
            WifiNoteFragment wifiNoteFragment = WifiNoteFragment.newInstance(1);
            wifiNoteFragment.setOnWifiNoteClick(this);
            DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiNoteFragment, "wifinote");
        } else {
            fragment.setOnWifiNoteClick(this);
            fragment.loadLoading();
        }
        ThreadHelper.postDelayed(new Runnable() {
            @Override
            public void run() {
                //WifiHelper.startScan(LivePlayerController.this);
            }
        }, 1000);
    }

    @Override
    public void onWiFiAvailable(final List<String> wifis) {
        ThreadHelper.post(new Runnable() {
            @Override
            public void run() {
                AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
                DialogFragmentHelper.removeFragment(activity.getSupportFragmentManager(), "wifinote");
                if (wifis == null || wifis.isEmpty()) {
                    return;
                }
                ArrayList<String> wifi = new ArrayList<String>();
                wifi.addAll(wifis);
                WifiSelectDialogFragment wifiSelectDialogFragment = WifiSelectDialogFragment.newInstance(wifi);
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiSelectDialogFragment);
            }
        });
    }

    @Override
    public void onNoWiFi() {
        ThreadHelper.post(new Runnable() {
            @Override
            public void run() {
                AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
                WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), "wifinote");
                if (fragment == null) {
                    WifiNoteFragment wifiNoteFragment = WifiNoteFragment.newInstance(2);
                    wifiNoteFragment.setOnWifiNoteClick(LivePlayerController.this);
                    DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiNoteFragment, "wifinote");
                } else {
                    fragment.loadFailure();
                }
            }
        });
    }

    @Override
    public void onWiFiConnected() {
        ThreadHelper.post(new Runnable() {
            @Override
            public void run() {
                AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
                DialogFragmentHelper.removeFragment(activity.getSupportFragmentManager(), "wifinote");
            }
        });
    }

    @Override
    public void wifiNoEnable() {
        ThreadHelper.post(new Runnable() {
            @Override
            public void run() {
                AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
                WifiNoteFragment fragment = (WifiNoteFragment) DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), "wifinote");
                if (fragment == null) {
                    WifiNoteFragment wifiNoteFragment = WifiNoteFragment.newInstance(2);
                    wifiNoteFragment.setOnWifiNoteClick(LivePlayerController.this);
                    DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiNoteFragment, "wifinote");
                } else {
                    fragment.loadFailure();
                }
                ToastUtil.show(mContext, R.string.wifi_open_error);
            }
        });

    }

    @Override
    public void onResponse(final String requestTag, final String response) {
        if (requestTag.equals(requestCompanyVideoCommand)) {
            Message message = mDataHandler.obtainMessage(actionCompanyVideoCommand);
            Bundle bundle = new Bundle();
            bundle.putString("data", response);
            message.setData(bundle);
            mDataHandler.sendMessage(message);
        }
    }

    @Override
    public void onError(String requestTag, Throwable t) {

    }

    @Override
    public void onFinish() {

    }

    @Override
    public void onFail(String requestTag, String response) {

    }

    /**
     * 直播切换节目
     *
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        channelAdapter.setSelected(position);
        play(position);
    }

    private void sortData(List<TvProgram> mList) {
        Collections.sort(mList, this);
    }

    @Override
    public int compare(TvProgram lhs, TvProgram rhs) {
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = dateFormat.parse(lhs.getTime());
            date2 = dateFormat.parse(rhs.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 对日期字段进行升序，如果欲降序可采用after方法
        if (date1 != null && date1.before(date2)) {
            return -1;
        }
        return 1;
    }

    @Override
    public void callbackByfragment(String action, Bundle bundle) {
        switch (action) {
            case TVProgramsViewController.ACTION_PROGRAM_ITEMCLICK:
                if (bundle != null) {
                    TvProgram tvProgram = bundle.getParcelable("data");
                    if (tvProgram != null && !TextUtils.isEmpty(tvProgram.getUrl())) {
                        fromState = FROM_REVIEW;
                        play(tvProgram);
                        backgroundHandler.removeMessages(ACTION_PROGRAM_NEXT);
                        Message message = backgroundHandler.obtainMessage(ACTION_PROGRAM_NEXT);
                        Bundle bundle1 = new Bundle();
                        bundle1.putString("data", tvProgram.getUrl());
                        message.setData(bundle1);
                        backgroundHandler.sendMessage(message);
                    }
                }
                break;
            case CcpActivity.ACTION_RELOAD_CHANNEL:
            case MineFragment.ACTION_MINE_DIMISS:
            case SearchFragment.ACTION_SEARCH_DIMISS:
                _isHandPause = false;
                pcv_home.showTvprogram();
                refreshView(true);
                _isLive = true;
                String gid = SharePrefUtil.getIjkLiveId(mContext);
                if (!TextUtils.isEmpty(gid)) {
                    for (int i = 0; i < tvChannels.size(); i++) {
                        TvChannel tvChannel = tvChannels.get(i);
                        if (gid.equals(tvChannel.getGid())) {
                            _position = i;
                            break;
                        }
                    }
                }
                reStart();
                break;
            case TVHotViewController.ACTION_HOT_LIVE:
                if (bundle != null) {
                    int position = bundle.getInt("position", -1);
                    if (-1 != position) {
                        ((LinearLayoutManager) channel_recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, channel_recyclerView.getWidth() / 2 - 100);
                        if (!_isLive) { // 回看查看
                            _position = -1;
                        }
                        play(position);
                    }
                }
                break;
            case TVHotViewController.ACTION_HOT_VIDEO:
                if (bundle != null) {
                    Parcelable model = bundle.getParcelable("data");
                    if (model instanceof TvProgram) {
                        _isHotDialog = true;
                        TvProgram tvProgram = (TvProgram) model;
                        pcv_home.hideTvprogram();
                        play(tvProgram);
                        fromState = FROM_HOTVIEW;
                    }
                }
                break;
            case TVCompanyViewController.ACTION_COMPANY_DIMISS:
                _isHandPause = false;
                NfwxVideoPlayerManager.instance().resumeVideoPlayer();
                refreshView(true);
                break;
            case TVCompanyViewController.ACTION_COMPANY_VIDEO:
                if (bundle != null) {
                    CompanyVideo video = bundle.getParcelable("data");
                    if (video != null && !TextUtils.isEmpty(video.getUrl())) {
                        StringBuffer stringBuffer = new StringBuffer(video.getUrl() + "?");
                        stringBuffer.append("mobile=").append(AccountHelper.getInstance().getPhone(mContext));
                        stringBuffer.append("&videoid=").append(video.getVideo_id());
                        _isAudio = false;
                        _isLive = false;
                        _isShift = false;
                        _isCompany = true;
                        pcv_home.hideTvprogram();
                        findView(R.id.clip_btn).setVisibility(View.GONE);
                        findView(R.id.download_btn).setVisibility(View.GONE);
                        findView(R.id.share_btn).setVisibility(View.GONE);
                        findView(R.id.review_btn).setVisibility(GONE);
                        title_channel_name.setText(video.getTitle());
                        tv_vodplayer_back.setText("返回");
                        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
                        TVCompanyViewController.dismiss(activity.getSupportFragmentManager(), TVCompanyViewController.tag());
                        doPlayVideo(stringBuffer.toString());
                    }
                }
                break;
            default:
                super.callbackByfragment(action, bundle);
                break;
        }
    }

    @Override
    protected void nextProgram() {
        super.nextProgram();
        if (mNextProgram != null) {
            play(mNextProgram);
            fromState = FROM_REVIEW;
            backgroundHandler.removeMessages(ACTION_PROGRAM_NEXT);
            Message message = backgroundHandler.obtainMessage(ACTION_PROGRAM_NEXT);
            Bundle bundle1 = new Bundle();
            bundle1.putString("data", mNextProgram.getUrl());
            message.setData(bundle1);
            backgroundHandler.sendMessage(message);
            mNextProgram = null;
        }
    }

    @Override
    protected boolean hasNextProgram() {
        return mNextProgram != null;
    }

    @Override
    public int getFromState() {
        return fromState;
    }

    @Override
    public void release() {
        super.release();
        if (mDataHandler != null) {
            mDataHandler.removeCallbacksAndMessages(null);
        }
        if (backgroundHandler != null) {
            backgroundHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void playAdvertComplete() {
        if (!TextUtils.isEmpty(mPath)) {
            _isAdvert = false;
            doPlayVideo(mPath, 0);
        }
    }
}
